package co.com.travelsoft.dao.imp.maestras;


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import co.com.travelsoft.dao.interfaces.maestras.ClienteDAOInterface;
import co.com.travelsoft.entities.maestras.Cliente;
import co.com.travelsoft.util.exceptions.TsDAOException;
import co.com.travelsoft.util.exceptions.TsObjetNotFoundException;


/**
 * Dao {@link Cliente}
 * @author Juan Carlos Cardona
 * @since  23/04/2014
 * @version 1.0
 */
public class ClienteDAO extends HibernateDaoSupport implements ClienteDAOInterface {


    @Override
    public Cliente findById(String identificacion) throws TsObjetNotFoundException, TsDAOException {
	try {

	    String hql = "Select p from Cliente p where identificacion=:identificacion";
	    Query query = getSession().createQuery(hql);
	    query.setParameter("identificacion", identificacion);
	    Cliente result = (Cliente) query.uniqueResult();
	    if(result==null){
		throw new TsObjetNotFoundException("El Cliente con identificacion:" + identificacion + " no existe.");
	    }
	    return result;
	} catch (HibernateException e) {
	    throw new TsDAOException(e);
	}
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Cliente> getClientesList() throws TsDAOException {
	String hql = "Select c from Cliente c";
	Query query = getSession().createQuery(hql);
	List<Cliente> listReturn = query.list();

	return  listReturn;
    }


    @Override
    public void save(Cliente cliente) throws TsDAOException{
	Session session = null;
	Transaction tx = null;
	try{
	    session = getSession();
	    tx = session.beginTransaction();
	    session.save(cliente);
	    tx.commit();
	}catch(HibernateException e){
	    tx.rollback();
	    throw new TsDAOException(e);
	}
    }
}
